package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.WmMaterialConstants;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterial;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageTemplate fileStorageTemplate;

    /**
     * 查询素材列表
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult pageQuery(WmMaterialDto wmMaterialDto) {
        //1. 参数校验
        if (wmMaterialDto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDto.checkParam();
        //2.组装查询条件：wrapper
        //2.1 条件1：是否收藏
        //2.2 条件2：按创建时间倒序排列
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(wmMaterialDto.getIsCollection() == 1, WmMaterial::getIsCollection,wmMaterialDto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime);

        //3. 构建分页Page
        Page page = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());

        //4.开启查询
        page(page,wrapper);
        //select * from wm_material where is_collection = ? order by create_time desc limit ?,?

        //5. 组装结果返回： total  list
        PageResponseResult pr = new PageResponseResult((int)page.getCurrent(),
                (int)page.getSize(),(int)page.getTotal());
        pr.setData(page.getRecords());

        return pr;
    }

    /**
     * 素材上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        try {
            //1. 将文件上传到minio
            String originalFilename = multipartFile.getOriginalFilename();
            //1.1 处理一下文件名，确保唯一性
            String uuid = UUID.randomUUID().toString();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = uuid + suffix;
            String url = fileStorageTemplate.uploadImgFile("", filename, multipartFile.getInputStream());

            //2. 将minio返回的图片路径封装成wm_material素材对象
            WmMaterial material = new WmMaterial();
            //2.1 填充：url
            material.setUrl(url);
            //2.2 填充： user_id
            Integer userId = WmThreadLocalUtil.get();
            material.setUserId(userId);
            //2.3 填充：is_collection(默认0，不收藏)
            material.setIsCollection((short) 0);
            //2.4 填充：created_time
            material.setCreatedTime(new Date());

            //3.保存对象到数据库
            save(material);

            //4. 将素材对象返回给前端做数据回显
            return ResponseResult.okResult(material);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
    }

    /**
     * 收藏素材
     *
     * @param id
     */
    @Override
    public void collect(Integer id) {
        WmMaterial wmMaterial = getById(id);
        System.out.println("is_collection = " + wmMaterial.getIsCollection());
        wmMaterial.setIsCollection(WmMaterialConstants.IS_COLLECTION);//1
        System.out.println("当前图片素材未收藏，将is_collection值改为 = " + wmMaterial.getIsCollection());
        updateById(wmMaterial);
    }

    /**
     * 删除图片素材
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        removeById(id);
    }

    /**
     * 取消收藏图片素材
     *
     * @param id
     */
    @Override
    public void cancelCollect(Integer id) {
        WmMaterial wmMaterial = getById(id);
        System.out.println("is_collection = " + wmMaterial.getIsCollection());
        wmMaterial.setIsCollection(WmMaterialConstants.IS_NOT_COLLECTION);//1
        System.out.println("当前图片素材已收藏，将is_collection值改为 = " + wmMaterial.getIsCollection());
        updateById(wmMaterial);
    }
}
